<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2//EN">
<html><head><title>Programming in Lua : 9.1</title>
<link rel="stylesheet" type="text/css" href="pil.css">
</head>
<body>
<p class="warning">
<A HREF="contents.html"><IMG TITLE="Programming in Lua (first edition)" SRC="capa.jpg" ALT="" ALIGN="left"></A>This first edition was written for Lua 5.0. While still largely relevant for later versions, there are some differences.<BR>The third edition targets Lua 5.2 and is available at <A HREF="http://www.amazon.com/exec/obidos/ASIN/859037985X/theprogrammil3-20">Amazon</A> and other bookstores.<BR>By buying the book, you also help to <A HREF="../donations.html">support the Lua project</A>.
</p>
<table width="100%" class="nav">
<tr>
<td width="10%" align="left"><a href="9.html"><img border="0" src="left.png" alt="Previous"></a></td>
<td width="80%" align="center"><a href="contents.html"><font face="Helvetica,Arial,sanserif">
<font color="gray">Programming in </font><font color="blue"> Lua</font>
</font></a></td>
<td width="10%" align="right"><a href="9.2.html"><img border="0" src="right.png" alt="Next"></a></td>
</tr>
<tr>
<td width="10%" align="left"></td>
<td width="80%" align="center"><a href="contents.html#P1">Part I. The Language</a>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<a href="contents.html#9">Chapter 9. Coroutines</a></td>
<td width="10%" align="right"></td></tr>
</table>
<hr/>
<p><h2>9.1 &ndash; Coroutine Basics</h2>

<p>Lua offers all its coroutine functions packed in the
<code>coroutine</code> table.
The <code>create</code> function creates new coroutines.
It has a single argument,
a function with the code that the coroutine will run.
It returns a value of type <code>thread</code>,
which represents the new coroutine.
Quite often, the argument to <code>create</code> is an anonymous function,
like here:
<pre>
    co = coroutine.create(function ()
           print("hi")
         end)
    
    print(co)   --> thread: 0x8071d98
</pre>

<p>A coroutine can be in one of three different states:
suspended, running, and dead.
When we create a coroutine, it starts in the suspended state.
That means that a coroutine does not run its body automatically
when we create it.
We can check the state of a coroutine with the <code>status</code> function:
<pre>
    print(coroutine.status(co))   --> suspended
</pre>
The function <code>coroutine.resume</code> (re)starts the execution of
a coroutine, changing its state from suspended to running:
<pre>
    coroutine.resume(co)   --> hi
</pre>
In this example,
the coroutine body simply prints <code>"hi"</code> and terminates,
leaving the coroutine in the dead state,
from which it cannot return:
<pre>
    print(coroutine.status(co))   --> dead
</pre>

<p>Until now, coroutines look like nothing more than a complicated
way to call functions.
The real power of coroutines stems from the <code>yield</code> function,
which allows a running coroutine to suspend its execution
so that it can be resumed later.
Let us see a simple example:
<pre>
    co = coroutine.create(function ()
           for i=1,10 do
             print("co", i)
             coroutine.yield()
           end
         end)
</pre>
Now, when we resume this coroutine,
it starts its execution and runs until the first <code>yield</code>:
<pre>
    coroutine.resume(co)    --> co   1
</pre>
If we check its status,
we can see that the coroutine is suspended
and therefore can be resumed again:
<pre>
    print(coroutine.status(co))   --> suspended
</pre>
From the coroutine's point of view,
all activity that happens while it is suspended
is happening inside its call to <code>yield</code>.
When we resume the coroutine,
this call to <code>yield</code> finally returns
and the coroutine continues its execution
until the next yield or until its end:
<pre>
    coroutine.resume(co)    --> co   2
    coroutine.resume(co)    --> co   3
    ...
    coroutine.resume(co)    --> co   10
    coroutine.resume(co)    -- prints nothing
</pre>
During the last call to <code>resume</code>,
the coroutine body finished the loop and then returned,
so the coroutine is dead now.
If we try to resume it again,
<code>resume</code> returns <B>false</B> plus an error message:

<pre>
    print(coroutine.resume(co))
    --> false   cannot resume dead coroutine
</pre>
Note that <code>resume</code> runs in protected mode.
Therefore, if there is any error inside a coroutine,
Lua will not show the error message,
but instead will return it to the <code>resume</code> call.

<p>A useful facility in Lua is that
a pair resume-yield can exchange data between them.
The first <code>resume</code>, which has no corresponding <code>yield</code>
waiting for it, passes its extra arguments as arguments to the
coroutine main function:
<pre>
    co = coroutine.create(function (a,b,c)
           print("co", a,b,c)
         end)
    coroutine.resume(co, 1, 2, 3)    --> co  1  2  3
</pre>
A call to <code>resume</code> returns,
after the <B>true</B> that signals no errors,
any arguments passed to the corresponding <code>yield</code>:
<pre>
    co = coroutine.create(function (a,b)
           coroutine.yield(a + b, a - b)
         end)
    print(coroutine.resume(co, 20, 10))  --> true  30  10
</pre>
Symmetrically, <code>yield</code> returns any extra arguments
passed to the corresponding <code>resume</code>:
<pre>
    co = coroutine.create (function ()
           print("co", coroutine.yield())
         end)
    coroutine.resume(co)
    coroutine.resume(co, 4, 5)     --> co  4  5
</pre>
Finally, when a coroutine ends,
any values returned by its main function go to
the corresponding <code>resume</code>:
<pre>
    co = coroutine.create(function ()
           return 6, 7
         end)
    print(coroutine.resume(co))   --> true  6  7
</pre>

<p>We seldom use all these facilities in the same coroutine,
but all of them have their uses.

<p>For those that already know something about coroutines,
it is important to clarify some concepts before we go on.
Lua offers what I call <em>asymmetric coroutines</em>.
That means that it has a function to suspend the
execution of a coroutine
and a different function to resume a suspended coroutine.
Some other languages offer <em>symmetric coroutines</em>,
where there is only one function to transfer
control from any coroutine to another.

<p>
Some people call asymmetric coroutine <em>semi-coroutines</em>
(because they are not symmetrical,
they are not really <em>co</em>).
However, other people use the same term <em>semi-coroutine</em>
to denote a restricted implementation of coroutines,
where a coroutine can only suspend its execution when it is not
inside any auxiliary function, that is,
when it has no pending calls in its control stack.
In other words, only the main body of such semi-coroutines can yield.
A <em>generator</em> in Python is an example
of this meaning of semi-coroutines.

<p>Unlike the difference between symmetric and asymmetric coroutines,
the difference between coroutines and generators
(as presented in Python) is a deep one;
generators are simply not powerful enough to implement
several interesting constructions that we can write with true coroutines.
Lua offers true, asymmetric coroutines.
Those that prefer symmetric coroutines can implement them on
top of the asymmetric facilities of Lua.
It is an easy task.
(Basically, each transfer does a yield followed by a resume.)

<hr/>
<table width="100%" class="nav">
<tr valign="top">
<td width="90%" align="left">
<small>
  Copyright &copy; 2003&ndash;2004 Roberto Ierusalimschy.  All rights reserved.
</small>
</td>
<td width="10%" align="right"><a href="9.2.html"><img border="0" src="right.png" alt="Next"></a></td>
</tr>
</table>


</body></html>

